package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.entity.Dict;
import com.atguigu.srb.core.entity.dto.ExcelDictDto;
import com.atguigu.srb.core.listener.ExcelDtoDictListner;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author sofia
 * @since 2021-09-17
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
        public void importData(InputStream inputStream) {

        EasyExcel.read(inputStream, ExcelDictDto.class,new ExcelDtoDictListner(dictMapper)).sheet().doRead();
        log.info("Excel导入成功！");
    }

    @Override
    public List<ExcelDictDto> listDictData() {
        List<Dict> dicts = baseMapper.selectList(null);
        ArrayList<ExcelDictDto> excelDictDtos = new ArrayList<>(dicts.size());
        dicts.forEach(e->{
            ExcelDictDto excelDictDto = new ExcelDictDto();
            org.springframework.beans.BeanUtils.copyProperties(e, excelDictDto);
            excelDictDtos.add(excelDictDto);
        });
        return excelDictDtos;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        Map<String,Object> map = new HashMap<>();
        map.put("parentId", parentId);
        List<Dict> dictList = dictMapper.selectByMap(map);
        dictList.stream().forEach(dict -> {
            dict.setHasChildren(ishasChildren(dict.getId()));
        });
        return dictList;
    }

    /*
     * @Author sofia
     * @Description 判断当前节点是否有子节点
     * @Date  2021/11/27
     **/
    public Boolean ishasChildren(Long id){
        Map <String, Object> map = new HashMap<>();
        map.put("id", id); //
        List<Dict> dictList = dictMapper.selectByMap(map);
        if (CollectionUtils.isEmpty(dictList)){
            return false;
        }else {
            return true;
        }

    }






}
